package com.garlic.face.jlf.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;

import com.garlic.face.jlf.App;
import com.garlic.face.jlf.transaction.Means;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.math.BigDecimal;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

public class Tools {

    /**
     * 这个是 selfpos_60自带的机具 SN 号
     *
     * @return
     */
    public static String getDeviceNum() {
        return android.os.Build.SERIAL;
    }

    /**
     * 这个是 selfpos_60自带的机具 mac 号
     *
     * @return
     */
    public static String getMac() {
        String macSerial = null;
        String str = "";
        try {
            Process pp = Runtime.getRuntime().exec("cat /sys/class/net/eth0/address");
            InputStreamReader ir = new InputStreamReader(pp.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);

            for (; null != str; ) {
                str = input.readLine();
                if (str != null) {
                    macSerial = str.trim();// 去空格
                    break;
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return macSerial;
    }

    public static String asciiToString(String paramString) {
        StringBuilder sb = new StringBuilder();
        sb.append((char) Integer.parseInt(paramString));
        return sb.toString();
    }

    private static String getIpAddress(Context context) {
        NetworkInfo info = ((ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
        if (info != null && info.isConnected()) {
            // 3/4g网络
            if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
                try {
                    for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                        NetworkInterface intf = en.nextElement();
                        for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                            InetAddress inetAddress = enumIpAddr.nextElement();
                            if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                                return inetAddress.getHostAddress();
                            }
                        }
                    }
                } catch (SocketException e) {
                    e.printStackTrace();
                }

            } else if (info.getType() == ConnectivityManager.TYPE_WIFI) {
                //  wifi网络
                WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                String ipAddress = intIP2StringIP(wifiInfo.getIpAddress());
                return ipAddress;
            } else if (info.getType() == ConnectivityManager.TYPE_ETHERNET) {
                // 有限网络
                return getLocalIp();
            }
        }
        return null;
    }

    private static String intIP2StringIP(int ip) {
        return (ip & 0xFF) + "." +
                ((ip >> 8) & 0xFF) + "." +
                ((ip >> 16) & 0xFF) + "." +
                (ip >> 24 & 0xFF);
    }

    // 获取有限网IP
    private static String getLocalIp() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface
                    .getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf
                        .getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()
                            && inetAddress instanceof Inet4Address) {
                        return inetAddress.getHostAddress();
                    }
                }
            }
        } catch (SocketException ex) {

        }
        return "0.0.0.0";

    }

    public static String getMacAddressFromIp(Context context) {
        String mac_s = "";
        StringBuilder buf = new StringBuilder();
        try {
            byte[] mac;
            NetworkInterface ne = NetworkInterface.getByInetAddress(InetAddress.getByName(getIpAddress(context)));
            mac = ne.getHardwareAddress();
            for (byte b : mac) {
                buf.append(String.format("%02X:", b));
            }
            if (buf.length() > 0) {
                buf.deleteCharAt(buf.length() - 1);
            }
            mac_s = buf.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return mac_s;
    }

    public static boolean checkPrice(String old_price) {
        if (old_price.equals("0") || old_price.equals("0.") || old_price.equals("0.0") || old_price.equals("0.00")) {
            return false;
        } else {
            if (old_price.contains(".")) {
                String[] ps = old_price.split("\\.");
                if (ps.length == 2) {
                    String end = ps[1];
                    if (end.length() <= 2) {
                        return true;
                    } else {
                        return false;
                    }
                } else {
                    return false;
                }
            } else {
                return true;
            }
        }
    }

    public static String fen2yuan(String money) {
        /*BigDecimal bigMoney = new BigDecimal(money);
        BigDecimal feedRate = new BigDecimal("100");
        String returnStr = String.valueOf(bigMoney.divide(feedRate).setScale(2));*/
        return money;
    }

    public static int yuan2fen(String money) {
        String returnMoney = "";
        if (isNumber(money)) {
            BigDecimal feedRate = new BigDecimal(100);
            returnMoney = new BigDecimal(money).multiply(feedRate).setScale(0).toString();
        }
        return Integer.valueOf(returnMoney);
    }

    public static boolean isNumber(String str) {
        java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("^(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,2})?$"); // 判断小数点后2位的数字的正则表达式
        java.util.regex.Matcher match = pattern.matcher(str);
        return match.matches();
    }

    public static int getChannelFromMeta(Context context) {
        int value = getMetaData(context, "GARLIC_CHANNEL");
        return value;
    }

    private static int getMetaData(Context context, String key) {
        int value = 0;
        try {
            ApplicationInfo appInfo = context.getPackageManager()
                    .getApplicationInfo(context.getPackageName(),
                            PackageManager.GET_META_DATA);
            value = appInfo.metaData.getInt(key);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return value;
    }

    public static int getVersionCode() {
        Context context = App.getContext();
        int versionCode = 0;
        PackageManager packageManager = context.getPackageManager();
        PackageInfo packInfo;
        try {
            packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            versionCode = packInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }

    public static String bytes2HexString(byte[] data) {
        StringBuilder buffer = new StringBuilder();
        byte[] var5 = data;
        int var4 = data.length;

        for (int var3 = 0; var3 < var4; ++var3) {
            byte b = var5[var3];
            String hex = Integer.toHexString(b & 255);
            if (hex.length() == 1) {
                buffer.append('0');
            }
            buffer.append(hex);
        }
        return buffer.toString().toUpperCase();
    }

    public static void clearTrade() {
        Means.getInstance().getItemHead().clear();
        Means.getInstance().getRec_Tran().setQty(0.00);
        Means.getInstance().getRec_Tran().setCount(0.00);
        Means.getInstance().getRec_Tran().setAmount(0.00);
        Means.getInstance().getRec_Tran().setCustcode("");
        Means.getInstance().getRec_Tran().setDisc_amt(0.00);
        Means.getInstance().getRec_Tran().setFlag(0);
        Means.getInstance().getRec_Tran().setLast_points(0.00);
        Means.getInstance().getRec_Tran().setTransnmbr("");
    }

    public static void putPref(String prefName, String key, String value) {
        SharedPreferences sp = App.getContext().getSharedPreferences(prefName, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString(key, value);
        editor.commit();
    }


    public static void putMapPref(String preferenceName, Map<String, Object> map) {
        SharedPreferences sp = App.getContext().getSharedPreferences(preferenceName, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();

        for (Map.Entry<String, Object> entry : map.entrySet()) {
            String key = entry.getKey();
            Object object = entry.getValue();
            if (object instanceof String) {
                editor.putString(key, (String) object);
            } else if (object instanceof Integer) {
                editor.putInt(key, (Integer) object);
            } else if (object instanceof Boolean) {
                editor.putBoolean(key, (Boolean) object);
            } else if (object instanceof Float) {
                editor.putFloat(key, (Float) object);
            } else if (object instanceof Long) {
                editor.putLong(key, (Long) object);
            } else {
                editor.putString(key, object.toString());
            }
        }

        editor.commit();
    }

    public static Object getPref(String preferenceName, String key, Object defaultObject) {
        SharedPreferences sp = App.getContext().getSharedPreferences(preferenceName, Context.MODE_PRIVATE);

        if (defaultObject instanceof String) {
            return sp.getString(key, (String) defaultObject);
        } else if (defaultObject instanceof Integer) {
            return sp.getInt(key, (Integer) defaultObject);
        } else if (defaultObject instanceof Boolean) {
            return sp.getBoolean(key, (Boolean) defaultObject);
        } else if (defaultObject instanceof Float) {
            return sp.getFloat(key, (Float) defaultObject);
        } else if (defaultObject instanceof Long) {
            return sp.getLong(key, (Long) defaultObject);
        } else if (defaultObject instanceof Set) {
            return sp.getStringSet(key, (Set<String>) defaultObject);
        }

        return null;
    }

    public static String getFormatNumber(double number) {
        return String.format("%.2f", number);
    }

    public static void copyShopInfoToMemory(){
        String prefShopName = (String) Tools.getPref(App.CONFIG_INFO, App.SHOP_NAME, "");
        String prefShopNo = (String) Tools.getPref(App.CONFIG_INFO, App.SHOP_NO, "");
        String prefPosNo = (String) Tools.getPref(App.CONFIG_INFO, App.POS_NO, "");
        String prefPosIp = (String) Tools.getPref(App.CONFIG_INFO, App.POS_IP, "");
        int prefPosPort = (int) Tools.getPref(App.CONFIG_INFO, App.POS_PORT, 0);

        Means.getInstance().setShopName(prefShopName);
        Means.getInstance().setShopno(prefShopNo);
        Means.getInstance().setPosno(prefPosNo);
        Means.getInstance().setPosIp(prefPosIp);
        Means.getInstance().setPosPort(prefPosPort);
    }

    public static boolean getNeedCloseWeight(){
        return (boolean) Tools.getPref(App.CONFIG_INFO, App.NEED_CLOSE_WEIGTH, false);
    }

    public static void setNeedCloseWeight(boolean needClose){
        SharedPreferences sp = App.getContext().getSharedPreferences(App.CONFIG_INFO, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putBoolean(App.NEED_CLOSE_WEIGTH, needClose);
        editor.commit();
    }

    public static boolean getNeedInsertSQL(){
        return (boolean) Tools.getPref(App.CONFIG_INFO, App.NEED_INSERT_SQL, true);
    }

    public static void setNeedInsertSQL(boolean need){
        SharedPreferences sp = App.getContext().getSharedPreferences(App.CONFIG_INFO, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putBoolean(App.NEED_INSERT_SQL, need);
        editor.commit();
    }

    public static String formatTime() {
        try {
            /*SimpleDateFormat sdformat = new SimpleDateFormat("yyyyMMddHHmmss", Locale.CHINESE);
            Date date = sdformat.parse(time);*/
            SimpleDateFormat sdformat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.CHINESE);
            return sdformat.format(new Date());
        } catch (Exception e) {
            return "";
        }
    }

    public static String getLanguage() {
        return (String) Tools.getPref(App.CONFIG_INFO, App.LANGUAGE_KEY, "auto");
    }

    public static void setLanguage(String language) {
        SharedPreferences sp = App.getContext().getSharedPreferences(App.CONFIG_INFO, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString(App.LANGUAGE_KEY, language);
        editor.commit();
    }
}
